package upicgame.game.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import upicgame.entity.Game;
import upicgame.utils.Page;
import upicgame.game.service.GameService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.util.List;

/*
 *Created by GHW
 *Description:后台管理，game Controller
 *2019/12/17 11:15
 */
@Controller
public class GameController {
    @Resource
    private GameService gs;

    //添加游戏
    //文件上传
    @RequestMapping(value = "addGame", produces = "text/html;charset=UTF-8")
    public String addGame(Model model, HttpServletRequest request,
                          MultipartFile img,
                          String name,
                          String developer,
                          String description,
                          Double price,
                          Double discountprice,
                          String platform,
                          String tag) {
        try {
            //文件上传开始
            //获取文件原名
            String fileName = img.getOriginalFilename();
            //获取路径
            String path = request.getSession().getServletContext().getRealPath("img/gameImg");
            //创建新文件，并放入指定路径
            File file = new File(path);
            if (!file.exists()) {
                //无此文件夹则新建(img/gameImg)
                //mkdir和mkdirs的区别：mkdir只会创建一级目录,mkdirs会创建多级目录
                //比如img/gameImg只能使用mkdirs，用mkdir则不会创建任何文件夹，会直接返回false
                file.mkdirs();
            }
            //断言 如果fileName为空，则直接抛出异常，不往下执行
            assert fileName != null;
            //将上传文件写入到指定的路径下的文件里
            img.transferTo(new File(path, fileName));
            System.out.println(path);
            System.out.println(fileName);
            //赋值
            Game game = new Game();
            game.setName(name);
            game.setDescription(description);
            game.setDeveloper(developer);
            game.setDiscountprice(discountprice);
            game.setImg(fileName);
            game.setPlatform(platform);
            game.setPrice(price);
            game.setTag(tag);
            //文件上传结束
            //判断游戏名是否重复
            boolean ok = gs.addGame(game);
            if (ok) {
                gs.addGame(game);
                model.addAttribute("game", game);
                //返回给前端一个字符串，前端使用jQuery显示成功和失败字样
                model.addAttribute("success", "添加成功");
                System.out.println("From Controller [添加成功] 新加游戏名：[" + game.getName() + "]");
            } else {
                System.out.println("From Controller [添加失败] 原因[库中已有此游戏，游戏名重复，请重新添加]");
                model.addAttribute("msg", "库中已有此游戏");
            }
            return "gameAdd.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller [添加游戏出现异常，请检查]");
            return "添加游戏时出错";
        }
    }

    //游戏全查
    @RequestMapping("findAllGame")
    public String findAllGame(Model model) {
        try {
            List<Game> list = gs.findAllGame();
            if (list != null) {
                model.addAttribute("gameList", list);
                System.out.println("From Controller [findAllGame]:"+list);
                return "index.jsp";
            } else {
                return "游戏列表为空";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "加载游戏列表出错";
        }
    }

    //游戏分页全查
    @RequestMapping("findAllGameByPage")
    public String findAllGameByPage(Model model, Integer pageNum) {
        try {
//       如果当前页为空，那么当前页=1
            if (pageNum == null) {
                pageNum = 1;
            }
//      查找总数据条数
            int count = gs.findCount();
//      分页查出所有游戏，game返回list结果集
            List<Game> game = gs.findAllGameByPage(pageNum, 3);
//      将game放入page中
            Page<Game> p = new Page<>(pageNum, 3, game);
//      设置总条数
            p.setTotalCount(count);
            model.addAttribute("page", p);
            return "gameList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller:findAllGameByPage 抛出异常");
        }
        return "查找出错，请检查";
    }

    //通过id查询到游戏
    //文件上传
    @RequestMapping(value = "updateInfo", produces = "text/html;charset=UTF-8")
    public String updateGameById(Model model, Integer id) {
        try {
            assert id != null;
            Game game = gs.findGameById(id);
            model.addAttribute("game", game);
            return "gameInfo.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller [updateInfo]:查找出错");
        }
        return null;
    }

    //游戏信息修改
    @RequestMapping(value = "updateGame", produces = "text/html;charset=UTF-8")
    public String updateGame(Model model, HttpServletRequest request,
                             Integer id, String name, String developer, Double price, Double discountprice,
                             MultipartFile upload, String platform, String tag, String description, String oldImg) {
        try {
            Game game;
            if (!upload.isEmpty()) {
                //upload非空
                //获取原来文件名
                String fileName = upload.getOriginalFilename();
                File file = new File(request.getSession().getServletContext().getRealPath("img/gameImg"));
                if (!file.exists()) {
                    boolean isMkdirs = file.mkdirs();
                    System.out.println("File create:" + isMkdirs);
                }
                if (fileName != null) {
                    //文件名不为空
                    upload.transferTo(new File(file, fileName));
                    System.out.println("上传的文件名是：" + fileName);
                    game = gs.findGameById(id);
                    game.setName(name);
                    game.setPrice(price);
                    game.setDiscountprice(discountprice);
                    game.setDeveloper(developer);
                    game.setTag(tag);
                    game.setDescription(description);
                    game.setPlatform(platform);
                    //使用上传的图片
                    game.setImg(fileName);
                    String path = request.getSession().getServletContext().getRealPath("img/gameImg");
                    System.out.println("输出path目录：" + path);
                } else {
                    //文件名为空
                    game = gs.findGameById(id);
                }
                gs.updateGame(game);
                model.addAttribute("game", game);
            } else {
                //upload为空
                game = gs.findGameById(id);
                game.setName(name);
                game.setPrice(price);
                game.setDiscountprice(discountprice);
                game.setDeveloper(developer);
                game.setTag(tag);
                game.setDescription(description);
                game.setPlatform(platform);
                //使用原来的图片
                game.setImg(oldImg);
                gs.updateGame(game);
                model.addAttribute("game", game);
            }
            return "findAllGameByPage";
            //文件上传结束
        } catch (Exception e) {
            e.printStackTrace();
            return "修改游戏时出错";
        }
    }

    //删除游戏
    @RequestMapping(value = "deleteGame")
    public String deleteGame(Integer id) {
        try {
            assert id != null;
            gs.deleteGame(id);
            return "findAllGameByPage";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("From Controller [deleteGame]:删除游戏出错，请检查");
        }
        return null;
    }
}
